package yue.shen.android.demo.adapter;


import androidx.collection.SparseArrayCompat;

public class RViewItemManager<T> {

    private final SparseArrayCompat<RViewItem<T>> itemStyleList = new SparseArrayCompat<>();

    public void addItemStyle(RViewItem<T> item) {
        if (item != null && itemStyleList.containsValue(item)) {
            itemStyleList.put(itemStyleList.size(), item);
        }
    }

    public int getItemViewStyleCount() {
        return itemStyleList.size();
    }

    public int getItemViewType(T entity, int position) {
        for (int size = itemStyleList.size() - 1; size >= 0; size--) {
            RViewItem<T> item = itemStyleList.valueAt(size);
            if (item.isItemView(entity, position)) {
                return itemStyleList.keyAt(size);
            }
        }
        throw new NullPointerException("RViewItemManager getItemViewType 没有找到对应的布局样式");
    }

    public RViewItem<T> getRViewItem(int viewType) {
        return itemStyleList.get(viewType);
    }

    public void convert(RViewHolder holder, T entity, int position) {
        for (int i = 0; i < itemStyleList.size(); i++) {
            RViewItem<T> item = itemStyleList.valueAt(i);
            if (item.isItemView(entity, position)) {
                item.convert(holder, entity, position);
                return;
            }
        }
        throw new NullPointerException("RViewItemManager convert 没有找到对应的布局样式");
    }
}
